<template>
  <x-dialog v-if="equ === 'h5'" :title="name" :describe="describe" width="85.333vw" :loading="loading"
    @on-submit="onSubmit" @on-close="onClose">
    <form-content :data-list="list" :check-field="checkField" />
  </x-dialog>
  <modal v-else :mask="false" :show="showModal" :height="545" @onCancel="onClose">
    <template #header>
      <div class="pc-content">
        <div v-if="name" class="header-title inline-block">
          {{ name }}
        </div>
        <div v-if="describe" class="header-description">
          {{ describe }}
        </div>
      </div>
    </template>
    <template #default>
      <div>
        <form-content :data-list="list" :check-field="checkField" />
      </div>
    </template>
    <template #footer>
      <div class="flc mt-30px">
        <div class="submit-btn" @click="onSubmit">
          提交
        </div>
      </div>
    </template>
  </modal>
</template>
<script lang="ts" setup name="XModalForm">
import { getForm, putForm, getLastFill, ecsForm } from '@/apis/form';
import { useTost, closeSome } from '@/utils/comps';
import { useTtsaStore } from '@/store/ttsa';
import { equ } from '../../../../package-env';
import { MODE } from '@/constants/ttsa';
import { table } from 'console';

const props = defineProps(['id', 'isNav', 'cfg']);
const emit = defineEmits(['unmount']);
const name = ref('');
const describe = ref('');
const list = ref([]);
const loading = ref(false);
const checkField = ref();
const submitStatus = ref(false);
const showModal = ref(true);

const ttsaStore = useTtsaStore();

const onClose = () => {
  if (props?.cfg?.event_click) {
    const { jump_type, content_id, content_node_id } = props.cfg?.event_click || {}
    if (jump_type && !content_id && !content_node_id) {
      ttsaStore.next(ttsaStore.peekBackInfo)
    } else {
      props.cfg?.handEvent?.();
    }
  } else if (!props.isNav && ttsaStore.mode !== MODE.QA) ttsaStore.next();
  emit('unmount');
  showModal.value = false;
}

const submitClose = () => {
  if (!props.isNav && ttsaStore.mode !== MODE.QA) ttsaStore.next();
  emit('unmount');
  showModal.value = false;
}

// 0=单行，1=多行，2=图片，3=单选，4=多选
onBeforeMount(async () => {
  closeSome({ form: true })
  loading.value = true;
  const res = await getForm(props.id);
  loading.value = false;
  name.value = res.name;
  describe.value = res.description;
  const formData = await getLastFill(props.id);
  list.value = res.params.map((item) => {
    let value = item.type === 4 ? [] : '';
    const itemData = formData[item.name];
    if (itemData) {
      if (item.type === 3) {
        const pi = item.options.find((n) => n.name === itemData);
        value = pi.value;
      } else if (item.type === 4) {
        const map = itemData.split('丨');
        const mapOpt = item.options.reduce((r, c) => ({ ...r, [c.name]: c.value }), {});
        value = map.map((m) => mapOpt[m])
      } else {
        value = itemData;
      }
    }
    return { ...item, value };
  })
  if (res.interval_type === 3) {
    ttsaStore.break = true
  } else if (res.interval_type === 2 && res.interval) {
    setTimeout(onClose, res.interval * 1000);
  }
})

const getValue = (item) => {
  if (item.type === 3) {
    const pi = item.options.find((n) => n.value === item.value);
    return pi?.name || '';
  } else if (item.type === 4) {
    const map = item.options.reduce((r, c) => ({ ...r, [c.value]: c.name }), {});
    return item.value.map((n) => map[n]).join('丨');
  } else {
    return item.value;
  }
}

const onSubmit = () => {
  submitStatus.value = true;
  const params = [];
  let phoneValue
  for (let i = 0; i < list.value.length; i++) {
    const { must, value, name, options } = list.value[i];
    if (must && (value === '' || value.length < 1)) {
      useTost(`请${options && options.length ? '选择' : '输入'}${name}~`);
      checkField.value = name;
      submitStatus.value = false;
      return;
    }
    const v = getValue(list.value[i])
    if (['联系方式', '联系电话'].includes(name)) phoneValue = v
    params.push({ name, value: v });
  }
  loading.value = true;
  putForm({ table_id: props.id, params })
    .then(() => {
      const pc = ['dbbba0a7403f4134adca441eddf4338c', 'e926efd02c574e4b9b358600d3b2981a', '8210514be9424b21a716c9f5094165ce']
      const h5 = ['d1e23602d2ec476fb0e2c58d19b9f79a', '7e2f9ab39e51439e9e42bee129b7a0c4', 'a3ea54cb922c4073b4720655c4ca9a47']
      const arr = equ === 'h5' ? h5 : pc
      if (arr.includes(props.id) && phoneValue && /^1[3456789]\d{9}$/.test(phoneValue)) {
        ecsForm({ MobilePhone: phoneValue, DataSource: `有灵${equ}客户端` })
      }
      useTost('提交成功', equ === 'pc' ? 'pc-success' : 'success', equ === 'pc')
      submitClose()
    })
    .finally(() => {
      loading.value = false;
      submitStatus.value = false;
    });
}
</script>
<style scoped lang="scss">
.title {
  color: #000000;
  font-size: 16px
}

.description {
  color: rgba(0, 0, 0, 0.65);
  font-size: 10px;
}

:deep(.content) {
  margin-left: 6.5px;
}

.submit-container {
  // @apply backdrop-filter backdrop-blur-[44px];
  // background: rgba(4, 15, 44, 0.75);

  .submit-icon {
    width: 115px;
    height: 38.5px;
  }
}

.pc-content {
  color: #fff;

  .header-title {
    position: relative;
    font-weight: 600;
    font-size: 20px;
    line-height: 26px;
    letter-spacing: 2px;
    color: #000000;
  }

  .header-description {
    @apply mt-3 text-[14px] text-center;
    color: rgba(0, 0, 0, 0.65);
    letter-spacing: 1px;
    line-height: 20px;
  }
}

.submit-btn {
  @apply flc cursor-pointer font-bold;
  width: 140px;
  letter-spacing: 4px;
  height: 40px;
  background: #FFFFFF;
  box-shadow: 0px 2px 30px 0px rgba(25, 47, 87, 0.05);
  border-radius: 22px;
  opacity: 0.6;

  &:hover {
    opacity: 0.8;
  }
}


.form-content {
  height: auto;
  color: #fff;
}

// :global(.modal-wrapper) {
//   @media screen and (min-width: 1440px) {
//     .modal-wrapper {
//       transform: translateX(-93%);
//     }
//   }

//   left: -13% !important;
// }
</style>
